from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from lib import expected_conditions as MEC


class BasePage(object):
    """所有页面类的基类，对webdriver常用方法的二次封装"""
    def __init__(self, driver):
        """初始化driver"""
        self.driver = driver

    # 打开当前页面的方法
    def open(self, url):
        """输入网址，并且将页面最大化"""
        self.driver.maximize_window()
        self.driver.get(url)

    def find_element(self, locator, timeout=10):
        """
        对于find_element方法的封装，加入了显式等待
        :param locator:
        :param timeout: 元素定位的超时时间，默认为10s
        :return:
        """
        return WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(locator))

    def find_elements(self, locator, timeout=10):
        return WebDriverWait(self.driver, timeout).until(EC.presence_of_all_elements_located(locator))

    def click(self, locator, ignored_exceptions=None):
        wait = WebDriverWait(self.driver, 10, ignored_exceptions=ignored_exceptions)
        wait.until(lambda x: True if x.find_element(*locator).click() else True)

    def click_element(selfself, webElement):
        webElement.click()

    def send_keys(self, locator, text, is_clear=False):
        element = self.find_element(locator)
        if is_clear: element.clear()
        element.send_keys(text)

    def get_text(self, locator, until_not_null=False):
        element = self.find_element(locator)
        if not until_not_null:
            return element.text
        else:
            return WebDriverWait(self.driver, 10).until(
                MEC.text_not_null(locator)
            )
